/* vue build 项目配置 */
// const fs = require('fs');
const ora = require('ora');
const path = require('path');
const webpack = require('webpack');
const CleanPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('mini-css-extract-plugin');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const cssnano = require('cssnano');

const webpackConfig = require('./base.config');

const params = process.env.npm_lifecycle_script.split(' ')[2];
const multipleEntry = require('./multipleEntry');

webpackConfig.module.rules.push({
    test: /\.css$/,
    exclude: /node_modules/,
    use: [ExtractTextPlugin.loader, 'css-loader', 'postcss-loader'],
});

webpackConfig.mode = 'production';
webpackConfig.output = {
    filename: 'js/[name].[chunkhash:7].js',
    chunkFilename: 'js/[name].[chunkhash:7].js',
    publicPath: './',
};

webpackConfig.optimization = {
    splitChunks: {
        chunks: 'async', // 必须3选1： "initial" | "all"(默认就是all) | "async"
        // 大于30KB才单独分离成chunk
        minSize: 30000, // 最小文件，默认0
        maxAsyncRequests: 5, // 最大异步请求数， 默认1
        maxInitialRequests: 3, // 最大初始化请求数，默认1
        name: true, // 名称，此选项可接收 function
        cacheGroups: { // 设置缓存的 chunks
            priority: false, // 缓存组优先级
            polyfill: { // key 为 entry 中定义的入口名称
                name: 'vendor', // 要缓存的 分隔出来的 chunk 名称
                reuseExistingChunk: true, // 可设置是否重用该chunk
                chunks: 'initial',
                minChunks: 2,
            },
            Vue: {
                name: 'Vue',
                chunks: 'initial',
                minChunks: 2
            },
            app: {
                name: 'app',
                chunks: 'initial',
                minChunks: 2
            },
        }
    },
    minimizer: [
        // js mini
        new UglifyJsPlugin({
            cache: true,
            parallel: true,
            sourceMap: false,
        }),
        new OptimizeCSSPlugin({
            cssProcessor: cssnano,
            cssProcessorPluginOptions: {
                preset: ['default', {
                    sourcemap: true,
                    safe: true,
                    discardComments: {
                        removeAll: true,
                    },
                    discardUnused: false,
                    zindex: false
                }],
            },
        })
    ]
};

webpackConfig.plugins.push(
    new ExtractTextPlugin({
        filename: '../dist/css/[name].css',
        chunkFilename: '[id].css',
    }),
    new webpack.HashedModuleIdsPlugin(),
    new CleanPlugin(['dist'], {
        root: path.join(__dirname, '../'),
        verbose: true,
        dry: false,
    }),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production'),
        },
    }),
);

if (params === '--analyze') {
    webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}

multipleEntry.pages.forEach((page) => {
    webpackConfig.plugins.push(
        new HtmlWebpackPlugin({
            title: page.title,
            filename: page.filename,
            template: page.template,
            inject: true,
            hash: true,
            chunks: ['polyfill', page.chunk],
            minify: {
                removeComments: true, // 移除HTML中的注释
                collapseWhitespace: true,
                removeEmptyAttributes: true,
            },
            chunksSortMode: 'dependency'
        })
    );
});

const spinner = ora('正在打包...');
spinner.start();

webpack(webpackConfig, (err) => {
    spinner.stop();
    if (err) throw err;

    console.log('  打包完成~\n');
    console.log('  提示:\n'
        + '  打包后的文件必须经过 HTTP 服务器访问.\n'
        + '  直接通过 file:// 方式打开无效.\n');
});
